/**
 * 支付相关服务
 */
const util = require('../utils/util.js');
const api = require('../config/api.js');
function payOrder(orderId) {
    return new Promise(function(resolve, reject) {
        let order = orderId.toString()
        util.request(api.PayPrepayId, {
            orderId: order,
            channel: 2
        },'POST').then((res) => {
            if (res.errno === 0) {
                const payParam = res.data;
                if(res.data.signType === 'YZJCUSTOMER') {
                    resolve(res);
                } else {
                    wx.requestPayment({
                        'timeStamp': payParam.timeStamp,
                        'nonceStr': payParam.nonceStr,
                        'package': payParam.package,
                        'signType': payParam.signType,
                        'paySign': payParam.paySign,
                        'success': function(res) {
                            resolve(res);
                        },
                        'fail': function(res) {
                            console.log(res);
                            reject(res);
                        },
                        'complete': function(res) {
                            reject(res);
                        }
                    });
                }
            } else {
                reject(res);
            }
        });
    });
}

function recharge(orderId) {
    return new Promise(function(resolve, reject) {
        util.request(api.PayPrepayId, {
            orderId: orderId,
            channel: 2
        },'POST').then((res) => {
            if (res.errno === 0) {
                const payParam = res.data;
                wx.requestPayment({
                    'timeStamp': payParam.timeStamp,
                    'nonceStr': payParam.nonceStr,
                    'package': payParam.package,
                    'signType': payParam.signType,
                    'paySign': payParam.paySign,
                    'success': function(res) {
                        resolve(res);
                    },
                    'fail': function(res) {
                        reject(res);
                    },
                    'complete': function(res) {
                        reject(res);
                    }
                });

                resolve(res);
            } else {
                reject(res);
            }
        });
    });
}

module.exports = {
    payOrder,
    recharge
};